package com.xy.job.admin.core.schedule

import java.util.concurrent.Delayed
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicLong
import kotlin.math.max

class ScheduleTaskList(
    /**
     * 过期时间
     */
    val expiration: AtomicLong = AtomicLong(0L),
) : Delayed {
    private val taskList = mutableListOf<ScheduleTask>()

    fun compareAndSetExpiration(expire: Long): Boolean {
        return expiration.getAndSet(expire) != expire
    }

    @Synchronized
    fun addTask(task: ScheduleTask) {
        taskList.add(task)
        task.scheduleTaskList = this
    }

    @Synchronized
    fun flush(flush: (ScheduleTask) -> Unit) {
        taskList.forEach(flush)
        taskList.clear()
        expiration.set(0L)
    }

    override fun getDelay(unit: TimeUnit): Long {
        val delayMs = expiration.get() - System.currentTimeMillis()
        val delay = unit.convert(delayMs, TimeUnit.MILLISECONDS).toDouble()
        return max(0.0, delay).toLong()
    }

    override fun compareTo(other: Delayed?): Int {
        if (other is ScheduleTaskList) {
            return compareValuesBy(this, other) { it.expiration.get() }
        }
        return 0
    }
}